import router from "./router";
import { loginStore } from "@/store/index";
import { submenuStore } from "@/store/submenu";
import { userinfo, editorUserinfo } from "@/api/login";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import AdminRoutes from "@/router/modules/admin";
import EditorRoutes from "@/router/modules/editor";
router.beforeEach((to, from, next) => {
  NProgress.start();
  const store = loginStore();
  const menuStore = submenuStore();
  let token = store.token;
  const auth = store.userInfo.auth;
  if(!auth) {
    store.RemoveToken();
    token = '';
  }
  /* 1 首次登录后，x掉浏览器，再次打开链接，会是空白的 因为cookie没有被销毁
  2.首次地址栏输入地址进入后，一级标签 不会自动选中首页，
  选中第二个一级标签后，退出登录，然后再重新登录，还是第二个一级标签，但是main里面是首页的内容 */
  if (token) {
    // 有权限
    if (to.path !== "/login") {
      if ((auth == 'admin' || auth == 'editor') && menuStore.menus.length == 0) {
        // 重新获取路由 并进行动态渲染
        console.log('1111');
        gotoRouter(to, next);
      } else {
        next()
      }
    } else {
      next("/");
    }
  } else {
    if (to.path !== "/login") {
      next("/login");
    } else {
      next();
    }
  }
});

router.onError(function () {
  router.push("/404");
});

router.afterEach((route) => {
  NProgress.done();
});

async function gotoRouter(to, next) {
  const store = loginStore();
  try {
    if (!sessionStorage.getItem("auth")) {
      store.RemoveToken();
      router.push('/login');
    }
    if (sessionStorage.getItem("auth") == "admin") {
      console.log('2222');
      const { data } = await userinfo();
      setRoute(data, AdminRoutes, to, next);
    } else {
      const { data } = await editorUserinfo();
      setRoute(data, EditorRoutes, to, next);
    }
  } catch (err) {
    store.RemoveToken();
    next();
  }
}
function setRoute(data, arr, to, next) {
  const store = loginStore();
  const menuStore = submenuStore();
  if (data.code == 200) {
    console.log('33333');
    menuStore.setMenus(arr);
    store.changeUserInfo(data.data);
    arr.forEach((item) => {
      router.addRoute(item);
    });
    next({ ...to, replace: true });
  } else {
    store.RemoveToken();
    next();
  }
}
